<script setup lang="tsx">
import { type PropType, ref, unref, reactive, h, computed, watch } from 'vue';
import { getBusinessObject, type ModdleElement } from 'bpmn-js/lib/util/ModelUtil';
import { debounce } from 'lodash-es';
import { PlusOutlined,FileSearchOutlined,FormOutlined } from '@ant-design/icons-vue';
import { Checkbox } from 'ant-design-vue';
import useElementUpdateListener from '@/components/design/hooks/useElementUpdateListener';
import catchUndefElement from '@/components/design/utils/CatchUndefElement';
import editor from '@/store/modules/editor';
import modeler from '@/store/modules/modeler';
import { setNameValue } from '@/components/design/bo-utils/nameUtil';
import { handleTree, getFormDataJson, getSubsequentNodes } from '@/utils/common';

import { getFormTree } from '@/api/form/index';
import { getOperActionList, getTempOperActionList } from '@/api/system/operAction/index';
import { getActionTempList } from '@/api/system/actionTemp/index';
import {
  runTypeOptions,
  runAgainOptions,
  runDataIsNullOptions,
  runModeOptions,
  jumpTypeOptions,
  subTaskRunOptions,
  parentTaskRunOptions,
  ServiceTaskTypes,
} from '@/components/design/components/DesignerCommCore/PanelOptions';
import {
  RowData,
  createData,
  createRunData,
  createHisData,
  defaultColumns,
} from '@/components/design/components/DesignerCommCore/columns';
import { message } from 'ant-design-vue';
import { taskAttr } from '@/store/modules/taskAttr';
import { processInfo } from '@/store/modules/processInfo';
import { useModal } from '@/hooks/useModal/useModal';
import SettingOrg from '@/components/setting/assigneeSetting.vue';
import EleListeners from '@/components/design/components/Panel/components/ElementExecutionListeners.vue';
import { createTaskData } from '@/components/design/components/DesignerCommCore/TaskAttr';
import { getFormConf } from '@/api/form/index';
import { formatFlowSortTree } from '@/views/flow/category/columns';
import { getFlowSortList } from '@/api/flow/sort';
import { flatTree } from '@/core/permission/utils';
import { cloneDeep } from 'lodash-es';
import { getFlowList } from '@/api/flow/index';
import SubFlowParentSetting from '@/components/setting/subFlow/index.vue';
import SubFlowSetting from '@/components/setting/subFlow/keyValueSetting.vue';
import { businessMethods } from '@/store/modules/businessMethod';

function updateElementName() {
  setNameValue(modeler().getActive as Element, taskInfo.value.TASK_NODE_NAME);
  //updateUserAssignProp('candidateUsers', scopedElement.id);
}
function updateElementId() {
  setIdValue(modeler().getActive as Element, taskInfo.value.TASK_NODE_NO);
  //updateUserAssignProp('candidateUsers', scopedElement.id);
}

const updateExModdleProp = debounce(
  function (
    element: BpmnElement,
    moddleElement: ModdleElement,
    propKey: string,
    propValue: unknown,
  ) {
    const modeling = modeler().getModeling;
    const exPropKey = `${editor().getProcessEngine}:${propKey}`;
    modeling!.updateModdleProperties(element, moddleElement, {
      [exPropKey]: propValue === '' ? undefined : propValue,
    });
  },
  300,
  { leading: true },
);

const props = defineProps({
  labelWidth: {
    type: Number as PropType<number>,
    default: 100,
  },
});

const taskAttrStore = taskAttr();
const assigneeLabel = ref<any>('设置处理人');
const [ModalRender, modalRef] = useModal();
const editFormRef = ref<any>(null);
const formKeyList = ref<any>([]);
//是不是开始节点
const isCallActivity = ref<boolean>(false);
let scopedElement: BpmnElement | undefined = undefined;
let scopedBO: ModdleElement | undefined = undefined;
const taskInfo = ref<object>({});
const editDrawerBindValue = reactive({
  defaultSelectData: [],
  runType: '',
});
const openMenuModal = async () => {
  editDrawerBindValue.runType = taskInfo.value.TASK_RUN_TYPE;
  editDrawerBindValue.defaultSelectData = taskInfo.value.TASK_RUN_DATA;
  ModalRender.show({
    title: '选择处理人',
    width: taskInfo.value.TASK_RUN_TYPE === 0 ? '70%' : '60%',
    // 是否显示右上角确定取消
    defaultExtra: true,
    destroyOnClose: true,
    content: () => {
      return <SettingOrg ref={editFormRef} defaultData={unref(editDrawerBindValue)}></SettingOrg>;
    },
    // 确定方法执行
    onOk: async (values) => {
      const res = await editFormRef.value?.handleSubmit();
      console.log(res);
      if (!res) return;
      taskInfo.value.TASK_RUN_DATA = res;
      console.log(taskInfo.value);
    },
  });
};
//是不是开始节点
const isStartEvent = ref<boolean>(false);
//是否事务节点
const isServicTask = ref<boolean>(false);
//是否转换节点
const isCCTask = ref<boolean>(false);
//是否执行节点
const isUserTask = ref<boolean>(false);
//是否结束节点
const isEndTask = ref<boolean>(false);
//节点类型
const userTaskType = ref<any>('');

const updateUserAssignProp = (key: string, value: string) => {
  updateExModdleProp(scopedElement!, scopedBO!, key, '${' + value + '}');
};
//删除组织结构标签
const handleClose = (record) => {
  taskInfo.value.TASK_RUN_DATA = taskInfo.value.TASK_RUN_DATA.filter(
    (item) => item.NO !== record.NO,
  );
};

//表单数据
const nodeFormOptions = ref<[]>();
const setSelectedTree = async () => {
  const res = await getFormTree();
  nodeFormOptions.value = handleTree(res.result, 'id', 'formSort');
  console.log(nodeFormOptions.value,"nodeFormOptions.value1111111111")
};
setSelectedTree();

const reloadElementData = async () =>
  catchUndefElement(async (element) => {
    console.log(element,modeler().getActive.type,"element111111111111111111")
    isStartEvent.value = false;
    isUserTask.value = false;
    isEndTask.value = false;
    isCCTask.value=false;
    isServicTask.value = false;
    scopedElement = element;
    scopedBO = getBusinessObject(element);
    taskInfo.value.TASK_NODE_NO = element.id;
    taskInfo.value.TASK_NODE_NAME = element.businessObject.name;
    if (element.businessObject.$type == 'bpmn:StartEvent') {
      isStartEvent.value = true;
    } else {
      //如果是UserTask类型的节点
      if (
        ['bpmn:UserTask', 'bpmn:ServiceTask','bpmn:EndEvent'].includes(
          modeler().getActive.type,
        )
      ) {
        if (
          element.incoming.length > 0 &&
          element.businessObject.incoming[0].sourceRef.$type == 'bpmn:StartEvent'
        ) {
          isStartEvent.value = true;
        } else {
          if (element.businessObject.$attrs != null&&modeler().getActive.type === 'bpmn:UserTask') {
            userTaskType.value = element.businessObject.$attrs['activiti:userTaskType'];
          if (userTaskType.value === 'ccTask') {
            taskInfo.value.TASK_TYPE = 'ccTask';
            taskInfo.value.TASK_RUN_MODE = 1;
            isCCTask.value=true;
          }
          else{
            isUserTask.value = true;
          }
        }
        }
        if (
          modeler().getActive.type == 'bpmn:EndEvent'
        ) {
          isEndTask.value = true;
        }
        if (modeler().getActive.type === 'bpmn:ServiceTask') {
          isServicTask.value = true;
        } 
      }
    }
  });
useElementUpdateListener(reloadElementData);


const activeKey = ref('EventDefinition');
const activeKeyChange=()=>{
  taskInfo.value.TASK_NODE_FORM="";
}
const transSortTreeData = (data: any[]): any[] => {
  return data.map((node) => ({
    value: node.sortId,
    label: node.sortName,
    nodeType: 'sort',
    children: node.children ? transSortTreeData(node.children) : [],
  }));
};
const transFlowTreeData = (data: any[]): any[] => {
  return data.map((node) => ({
    value: node.procDefId,
    label: node.procName,
    nodeType: 'flow',
    children: node.children ? transFlowTreeData(node.children) : [],
  }));
};
// 深度监听 profile 对象
watch(
  () => taskInfo.value.TASK_NODE_FORM,
  async (newVal, oldVal) => {
    if (oldVal != undefined && newVal !== oldVal) {
      const formConfItemList = await getFormConf({ id: taskInfo.value.TASK_NODE_FORM });
      if (formConfItemList.result.form_json != null && formConfItemList.result.form_json != '') {
        const mapJSON = JSON.parse(formConfItemList.result.form_json);
        formKeyList.value = getFormDataJson(mapJSON.list);
        taskInfo.value.TASK_NODE_FORM_DATA_POWER = formKeyList.value;
      }
    } else {
      if (
        taskInfo.value.TASK_NODE_FORM == '' ||
        taskInfo.value.TASK_NODE_FORM == null ||
        taskInfo.value.TASK_NODE_FORM == undefined
      ) {
        const formConfItemList = await getFormConf({ id: taskInfo.value.TASK_NODE_FORM });
        if (
          formConfItemList.result.form_json != null &&
          formConfItemList.result.form_json != ''
        ) {
          const mapJSON = JSON.parse(formConfItemList.result.form_json);
          formKeyList.value = getFormDataJson(mapJSON.list);
          taskInfo.value.TASK_NODE_FORM_DATA_POWER = formKeyList.value;
        }
      }
    }
  },
  { deep: true },
);
</script>

<style lang="less" scoped>
.tagboxs {
  height: 28px;
}
.ant-radio-button-wrapper-checked{
  background: rgba(42,97,255,0.1);
  color: #2A61FF;
  font-size:16px
}
/deep/.ant-tabs-ink-bar {
  display: none!important;
}
// .ant-tabs-nav{
//   width: 210px;
// height: 36px;
// background: #FFFFFF;
// border-radius: 4px;
// border: 1px solid rgba(21,39,77,0.2);
// }
</style>

<template>
  <a-card>
    <div v-if="isStartEvent" style="display: flex; justify-content: center; align-items: center" size="large">
      <a-radio-group v-model:value="activeKey" @change="activeKeyChange" :style="{ marginBottom: '8px' }">
        <a-radio-button value="EventDefinition">事件定义</a-radio-button>
        <a-radio-button value="StockEvent">内置事件</a-radio-button>
      </a-radio-group>
    </div>
    <a-form layout="vertical">
      <a-form-item v-if="isStartEvent" label="启动事件">
          <a-tree-select
              v-model:value="taskInfo.TASK_NODE_FORM"
              show-search
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择"
              allow-clear
              :tree-data="nodeFormOptions"
              :field-names="{
                children: 'children',
                label: 'name',
                value: 'id',
              }"
              tree-node-filter-prop="name"
        ></a-tree-select>
        </a-form-item>
        <a-form-item v-if="isStartEvent"  label="数据过滤">
          <div  style="
              border: 1px solid #e6e8eb;
              display: flex;
              justify-content: space-between;
              align-items: center;
          ">
            <a-space>
              <div style="overflow: auto" class="tagboxs">
                <a-tag style="background: rgba(42,97,255,0.1);color:#2A61FF" closable @close="handleClose(tag)" v-for="tag in taskInfo.TASK_RUN_DATA" :key="tag">
                  {{ tag.NAME }}
                </a-tag>
              </div>
            </a-space>
            <a-button style="border:none;border-radius:0;border-left:1px solid rgba(21,39,77,0.2);margin-left: auto" size="small" secondary type="info" @click="openMenuModal">
              <template #icon>
                <PlusOutlined style="width: 14px; height: 14px"/>
                </template>
            </a-button>
          </div>
        </a-form-item>
        <a-form-item v-if="isUserTask||isServicTask||isCCTask" label="标题">
          <a-input v-model:value="taskInfo.TASK_NODE_NO" disabled maxlength="32" @change="updateElementId" />
        </a-form-item>
        <a-form-item v-if="isUserTask||isServicTask||isCCTask"  label="编码">
          <a-input v-model:value="taskInfo.TASK_NODE_NAME" maxlength="20" @change="updateElementName" />
        </a-form-item>
        <a-form-item v-if="isUserTask"  label="执行动作">
          <div  style="
              border: 1px solid #e6e8eb;
              display: flex;
              justify-content: space-between;
              align-items: center;
          ">
            <a-space>
              <div style="overflow: auto" class="tagboxs">
                <a-tag style="background: rgba(42,97,255,0.1);color:#2A61FF" closable @close="handleClose(tag)" v-for="tag in taskInfo.TASK_RUN_DATA" :key="tag">
                  {{ tag.NAME }}
                </a-tag>
              </div>
            </a-space>
            <a-button style="border:none;border-radius:0;border-left:1px solid rgba(21,39,77,0.2);margin-left: auto" size="small" secondary type="info" @click="openMenuModal">
              <template #icon>
                <FileSearchOutlined style="width: 14px; height: 14px"/>
                </template>
            </a-button>
          </div>
        </a-form-item>
        <a-form-item v-if="isCCTask||isEndTask"  label="出参设置">
          <div  style="
              border: 1px solid #e6e8eb;
              display: flex;
              justify-content: space-between;
              align-items: center;
          ">
            <a-space>
              <div style="overflow: auto" class="tagboxs">
                <a-tag style="background: rgba(42,97,255,0.1);color:#2A61FF" closable @close="handleClose(tag)" v-for="tag in taskInfo.TASK_RUN_DATA" :key="tag">
                  {{ tag.NAME }}
                </a-tag>
              </div>
            </a-space>
            <a-button style="border:none;border-radius:0;border-left:1px solid rgba(21,39,77,0.2);margin-left: auto" size="small" secondary type="info" @click="openMenuModal">
              <template #icon>
                <FormOutlined style="width: 14px; height: 14px"/>
                </template>
            </a-button>
          </div>
        </a-form-item>
        <a-form-item v-if="isServicTask"  label="赋值设置">
          <div  style="
              border: 1px solid #e6e8eb;
              display: flex;
              justify-content: space-between;
              align-items: center;
          ">
            <a-space>
              <div style="overflow: auto" class="tagboxs">
                <a-tag style="background: rgba(42,97,255,0.1);color:#2A61FF" closable @close="handleClose(tag)" v-for="tag in taskInfo.TASK_RUN_DATA" :key="tag">
                  {{ tag.NAME }}
                </a-tag>
              </div>
            </a-space>
            <a-button style="border:none;border-radius:0;border-left:1px solid rgba(21,39,77,0.2);margin-left: auto" size="small" secondary type="info" @click="openMenuModal">
              <template #icon>
                <FormOutlined style="width: 14px; height: 14px"/>
                </template>
            </a-button>
          </div>
        </a-form-item>
        <a-form-item v-if="isEndTask"  label="出参映射">
          <a-radio-group v-model:value="activeKey" @change="activeKeyChange" :style="{ marginBottom: '8px' }">
            <a-radio-button value="EventDefinition">参数映射器</a-radio-button>
            <a-radio-button value="StockEvent">公式定义器</a-radio-button>
          </a-radio-group>
          <div  style="
              border: 1px solid #e6e8eb;
              display: flex;
              justify-content: space-between;
              align-items: center;
          ">
            <a-space>
              <div style="overflow: auto" class="tagboxs">
                <a-tag style="background: rgba(42,97,255,0.1);color:#2A61FF" closable @close="handleClose(tag)" v-for="tag in taskInfo.TASK_RUN_DATA" :key="tag">
                  {{ tag.NAME }}
                </a-tag>
              </div>
            </a-space>
            <a-button style="border:none;border-radius:0;border-left:1px solid rgba(21,39,77,0.2);margin-left: auto" size="small" secondary type="info" @click="openMenuModal">
              <template #icon>
                <FormOutlined style="width: 14px; height: 14px"/>
                </template>
            </a-button>
          </div>
        </a-form-item>
      </a-form>
    </a-card>
</template>
